package com.shw.loco.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

import android.R.integer;

/**
 * @author HAHA
 */
public class InfoUtils {
	public static final int PORT485_RFID = 0;
	public static final int PORT232_GPS = 1;
	public static final int PORT485_LOCO = 2;
	public static final String RFID_REQ = "68010300BE72";
	public static final String DATE_REQ = "680102008D43";
	public static final String PAR_REQ = "6801050014D4";
	public static final String RFID_REQ_HEAD = "68";
	public static final String RFID_PORT = "RFID_PORT";
	public static final String GPSBD_PORT = "GPSBD_PORT";
	public static final String LOCO_PORT = "LOCO_PORT";
	public static final String RFID_TIME = "RFID_TIME";
	public static final String GPSBD_TIME = "GPSBD_TIME";
	public static final String CENTER_TIME = "CENTER_TIME";
	public static final String HEART_TIME = "HEART_TIME";
	public static final String PRECISION_IFNO = "PRECISION_IFNO";
	public static final String IP_INFO = "IP_INFO";
	public static final String IP_PORT = "IP_PORT";
	public static final String RFID_BAUDRATE = "RFID_BAUDRATE";
	public static final String GPSBD_BAUDRATE = "GPSBD_BAUDRATE";
	public static final String LOCO_BAUDRATE = "LOCO_BAUDRATE";
	public static final String SERVER_IP = "1.83.178.42";
	public static final String SERVER_PORT = "8909";
	public static final String SERVER_RFID_PORT = "/dev/ttySAC3";
	public static final String SERVER_GPS_PORT = "/dev/ttySAC2";
	public static final String SERVER_LOCO_PORT = "/dev/ttySAC1";
	public static final String SERVER_RFID_PAUDRATE = "57600";
	public static final String SERVER_GPS_PAUDRATE = "9600";
	public static final String SERVER_LOCO_PAUDRATE = "57600";
	public static final int SERVER_RFID_TIME = 100;
	public static final String SERVER_GPS_TIME = "8909";
	public static final int SERVER_DELAY = 200;
	public static final int GPS_DELAY = 200;
	public static final String OPERFLAG="OPERFLAG";
	public static final String ISDEBUG="ISDEBUG";
	public static final String LOCOTERMINAL="LOCOTERMINAL";
	public static String TERMINALID="0";

	//经度将度转度分
	public static String LonTolon(String info){
		BigDecimal bdHead=new BigDecimal(info.substring(0, 3));
		String tailInfo=info.substring(4);
		BigDecimal bdTail=new BigDecimal(tailInfo.substring(0,2)+"."+tailInfo.substring(2));
		return bdHead.add(bdTail.divide(new BigDecimal("60"),10, BigDecimal.ROUND_HALF_UP)).toString();
	}
	
	//维度将度转度分
		public static String LatTolat(String info){
			BigDecimal bdHead=new BigDecimal(info.substring(0, 2));
			String tailInfo=info.substring(3);
			BigDecimal bdTail=new BigDecimal(tailInfo.substring(0,2)+"."+tailInfo.substring(2));
			return bdHead.add(bdTail.divide(new BigDecimal("60"),10, BigDecimal.ROUND_HALF_UP)).toString();
		}
	
	// 判断奇数或偶数，位运算，最后一位是1则为奇数，为0是偶数
	public static int isOdd(int num) {
		return num & 0x1;
	}

	public static String coor2HexString(String info, boolean bool) {
		String headStr ="";
		String tailStr = "";
		String result = "";
		if(info.indexOf(".")>0){
			headStr = info.substring(0, info.indexOf("."));
			tailStr = info.substring(info.indexOf(".") + 1, info.length());
			if (bool) {// 速度
				result = InfoUtils.int2HexString(headStr, 6)
						+ InfoUtils.int2HexString(tailStr, 2);
			} else {// 里程坐标
				result = leftAdding(
						InfoUtils.int2HexString(headStr, 6)
								+ InfoUtils.int2HexString(coor_tailStr2int(tailStr), 2), "0", 8)
						+ "00000000";
			}
		}else{
			 headStr = info.substring(0, info.length());
			 if (bool) {// 速度
					result = InfoUtils.int2HexString(headStr, 8);
				} else {// 里程坐标
					result = leftAdding(
							InfoUtils.int2HexString(headStr, 6), "0", 8)
							+ "00000000";
				}
		}
		return result;
	}

	public static String coor_tailStr2int(String tailStr){
		try{
		if(Integer.valueOf(tailStr.substring(0, 3))>255){
			return "255";
		}else{
			return tailStr.substring(0, 3);
		}}catch (Exception e){
			return "255";
		}
	}
	
	// 4字节16进制转换为32位浮点数
	public static float byte2int_Float(byte b[]) {
		int bits = b[0] & 0xff | (b[1] & 0xff) << 8 | (b[2] & 0xff) << 16
				| (b[3] & 0xff) << 24;

		int sign = ((bits & 0x80000000) == 0) ? 1 : -1;
		int exponent = ((bits & 0x7f800000) >> 23);
		int mantissa = (bits & 0x007fffff);

		mantissa |= 0x00800000;
		// Calculate the result:
		float f = (float) (sign * mantissa * Math.pow(2, exponent - 150));

		return f;
	}

	// 4字节16进制转换为32位长正型数
	public static int byte2int(byte b[]) {
		int bits = b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16
				| (b[0] & 0xff) << 24;

		int sign = ((bits & 0x80000000) == 0) ? 1 : -1;
		int exponent = ((bits & 0x7f800000) >> 23);
		int mantissa = (bits & 0x007fffff);

		mantissa |= 0x00800000;
		// Calculate the result:
		int f = (int) (sign * mantissa * Math.pow(2, exponent - 150));

		return f;
	}

	// str扩大1000000倍
	public static String strCal1bw(String str) {
		String strResult = new BigDecimal(str)
				.multiply(new BigDecimal(1000000)).toString();
		if (strResult.indexOf(".") > 0)
			return strResult.substring(0, strResult.indexOf("."));
		else
			return strResult;
	}

	// str扩大1000000倍
	public static String strCal1b(String str) {
		String strResult = new BigDecimal(str).multiply(new BigDecimal(100))
				.toString();
		if (strResult.indexOf(".") > 0)
			return strResult.substring(0, strResult.indexOf("."));
		else
			return strResult;
	}

	// CRC16校验码基于XModem
	public static String CRC_16(byte[] bytes) {
		int crc = 0x00; // initial value
		int polynomial = 0x1021;
		for (int index = 0; index < bytes.length; index++) {
			byte b = bytes[index];
			for (int i = 0; i < 8; i++) {
				boolean bit = ((b >> (7 - i) & 1) == 1);
				boolean c15 = ((crc >> 15 & 1) == 1);
				crc <<= 1;
				if (c15 ^ bit)
					crc ^= polynomial;
			}
		}
		crc &= 0xffff;
		return leftAdding(Integer.toHexString(crc),"0", 4);
	}

	public static String CRC16s(byte[] buffer, int len) {
		int index = 0;
		int crc = 0;
		while (len-- > 0) {
			crc = (crc >> 8) | (crc << 8);
			crc ^= buffer[index++];
			crc ^= (crc & 0xff) >> 4;
			crc ^= (crc << 8) << 4;
			crc ^= ((crc & 0xff) << 4) << 1;
			crc &= 0xFFFF;
		}
		return Integer.toHexString(crc);
	}

	public static boolean checkCRC16(String info) throws Exception {
		String oldCRC = info.substring(info.length() - 4, info.length())
				.toUpperCase();
		String infos = info.substring(0, info.length() - 4);
		String newCRC = leftAdding(CRC_16(HexToByteArr(infos)).toUpperCase(),
				"0", 4);
		return newCRC.equals(oldCRC);
	}

	// -------------------------------------------------------
	public static int HexToInt(String inHex)// Hex字符串转int
	{
		return Integer.parseInt(inHex, 16);
	}

	// -------------------------------------------------------
	public static byte HexToByte(String inHex) throws Exception// Hex字符串转byte
	{

		return (byte) Integer.parseInt(inHex, 16);
	}

	// -------------------------------------------------------
	public static String Byte2Hex(Byte inByte)// 1字节转2个Hex字符
	{
		return String.format("%02x", inByte).toUpperCase();
	}

	// -------------------------------------------------------
	public static String ByteArrToHex(byte[] inBytArr)// 字节数组转转hex字符串
	{
		StringBuilder strBuilder = new StringBuilder();
		int j = inBytArr.length;
		for (int i = 0; i < j; i++) {
			strBuilder.append(Byte2Hex(inBytArr[i]));
			strBuilder.append(" ");
		}
		return strBuilder.toString();
	}

	// -------------------------------------------------------
	public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount)// 字节数组转转hex字符串，可选长度
	{
		StringBuilder strBuilder = new StringBuilder();
		int j = byteCount;
		for (int i = offset; i < j; i++) {
			strBuilder.append(Byte2Hex(inBytArr[i]));
		}
		return strBuilder.toString();
	}

	// -------------------------------------------------------
	// 转hex字符串转字节数组
	public static byte[] HexToByteArr(String inHex) throws Exception// hex字符串转字节数组
	{
		int hexlen = inHex.length();
		byte[] result;
		if (isOdd(hexlen) == 1) {// 奇数
			hexlen++;
			result = new byte[(hexlen / 2)];
			inHex = "0" + inHex;
		} else {// 偶数
			result = new byte[(hexlen / 2)];
		}
		int j = 0;
		for (int i = 0; i < hexlen; i += 2) {
			result[j] = HexToByte(inHex.substring(i, i + 2));
			j++;
		}
		return result;
	}

	/**
	 * 16进制char转换成整型
	 * 
	 * @param c
	 * @return
	 */
	public static int parse(char c) {
		if (c >= 'a')
			return (c - 'a' + 10) & 0x0f;
		if (c >= 'A')
			return (c - 'A' + 10) & 0x0f;
		return (c - '0') & 0x0f;
	}

	/**
	 * 十六进制字符串转换成字节数组
	 * 
	 * @param hexstr
	 * @return
	 */
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}

	public static String hexToDateStr(String hexStr) {
		int len = hexStr.length();
		StringBuffer dateStr = new StringBuffer("20");
		String second = hexStr.substring(0, 2);
		String minute = hexStr.substring(2, 4);
		String hour = hexStr.substring(4, 6);
		String week = hexStr.substring(6, 8);
		String day = hexStr.substring(8, 10);
		String mouth = hexStr.substring(10, 12);
		String year = hexStr.substring(12, 14);
		dateStr.append(year).append("-").append(mouth).append("-").append(day)
				.append(" ").append(hour).append(":").append(minute)
				.append(":").append(second);
		return dateStr.toString();
	}

	public static String dateToHexStr() throws Exception {
		StringBuffer dateStr = new StringBuffer("68010107");
		Date date = new Date();
		// dateStr.append(date.getSeconds()).append(date.getMinutes()).append(date.getHours()).append("00").append(date.getDay()).append(date.getDate()).append(date.getMonth()+1).append(String.valueOf(date.getYear()).substring(1,
		// 3));
		dateStr.append(leftAdding(String.valueOf(date.getSeconds()), "0", 2))
				.append(leftAdding(String.valueOf(date.getMinutes()), "0", 2))
				.append(leftAdding(String.valueOf(date.getHours()), "0", 2))
				.append("0")
				.append(date.getDay())
				.append(leftAdding(String.valueOf(date.getDate()), "0", 2))
				.append(leftAdding(String.valueOf(date.getMonth() + 1), "0", 2))
				.append(String.valueOf(date.getYear()).substring(1, 3));
		dateStr.append(CRC_16(HexToByteArr(dateStr.toString())));
		return dateStr.toString();
	}

	public static String dateToHexStrNoCRC() throws Exception {
		StringBuffer dateStr = new StringBuffer("");
		Date date = new Date();
		// dateStr.append(date.getSeconds()).append(date.getMinutes()).append(date.getHours()).append("00").append(date.getDay()).append(date.getDate()).append(date.getMonth()+1).append(String.valueOf(date.getYear()).substring(1,
		// 3));
		dateStr.append(leftAdding(String.valueOf(date.getSeconds()), "0", 2))
				.append(leftAdding(String.valueOf(date.getMinutes()), "0", 2))
				.append(leftAdding(String.valueOf(date.getHours()), "0", 2))
				.append("0")
				.append(date.getDay())
				.append(leftAdding(String.valueOf(date.getDate()), "0", 2))
				.append(leftAdding(String.valueOf(date.getMonth() + 1), "0", 2))
				.append(String.valueOf(date.getYear()).substring(1, 3));
		return leftAdding(dateStr.toString(), "0", 14);
	}

	public static String hexToWeekStr(String hexStr) {
		String result = "";
		int week = Integer.valueOf(hexStr.substring(6, 8));
		switch (week) {
		case 1:
			result = "星期一";
			break;
		case 2:
			result = "星期二";
			break;
		case 3:
			result = "星期三";
			break;
		case 4:
			result = "星期四";
			break;
		case 5:
			result = "星期五";
			break;
		case 6:
			result = "星期六";
			break;
		case 0:
			result = "星期日";
			break;
		default:
			break;
		}
		return result;
	}

	/**
	 * 将2进制字符串转成16进制字符串
	 * 
	 * @param addInfo
	 *            数据(2进制)
	 * @param length
	 *            目标byte的位数
	 * @return
	 */
	public static String binaryString2HexString(String addInfo, int length) {
		String tenInfo = new BigInteger(addInfo, 2).toString();
		int result = Integer.valueOf(tenInfo);
		// 将2个字节补满，左补0
		tenInfo = leftAdding(Integer.toHexString(result), "0", length);
		return tenInfo;
	}

	public static String leftAdding(String str, String info, int length) {
		int size = length - str.length();
		StringBuffer result = new StringBuffer("");
		for (int i = 0; i < size; i++) {
			result.append(info);
		}
		result.append(str);
		return result.toString();
	}

	public static String int2HexString(String str, int length) {
		String hexStr = Integer.toHexString(Integer.valueOf(str));
		hexStr = leftAdding(hexStr, "0", length);
		return hexStr;
	}

	/**
	 * 
	 * @param str1
	 *            里程计里程坐标
	 * @param str2
	 *            GPS里程坐标
	 * @param str3
	 *            常量值
	 * @return
	 */
	public static boolean compareInfo(String str1, String str2, String str3) {
		BigDecimal bd1 = new BigDecimal(str1);
		BigDecimal bd2 = new BigDecimal(str2);
		BigDecimal bd3 = new BigDecimal(str3);
		BigDecimal bd4 = new BigDecimal(0);
		bd4 = bd1.subtract(bd2);// 相减
		if (bd4.compareTo(new BigDecimal(0)) < 0) {// 小于0，则乘以-1转为正
			bd4 = bd4.multiply(new BigDecimal(-1));
		}
		if (bd4.compareTo(bd3) > 0) {// 大于0返回true，则说明使用gps里程坐标
			return true;
		} else {// 负责使用里程计里程坐标
			return false;
		}
	}
}